//
//  NetMrg.m
//  优学荟管理系统
//
//  Created by 星道 on 17/6/26.
//  Copyright © 2017年 星道三好. All rights reserved.
//

#import "NetMrg.h"

@implementation NetMrg

+ (NSURLSessionDataTask *)Get:(NSString *)UrlStr Auth:(BOOL)Auth Params:(NSDictionary *)Params Success:(void (^)(id))Success Fail:(void (^)(NSError *))Fail
{
    //1.获得请求管理者
    AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
    mgr.requestSerializer = [AFJSONRequestSerializer serializer];
    mgr.responseSerializer = [AFJSONResponseSerializer serializer];
    mgr.requestSerializer.timeoutInterval = 25;
    mgr.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/plain", @"text/html", nil];
    [mgr.requestSerializer setValue:@"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    //auth 加密
    if (Auth)
    {
        [mgr.requestSerializer setValue:[AccountTool shareAccountTool].currentAccount.authCode forHTTPHeaderField:@"auth"]; //Authorization

    } else {
        if (Params && Params.count > 0) {
            // 如果不用auth，那么action就一要跟在问号后面
            NSMutableDictionary *dict = [Params mutableCopy];
            UrlStr = [NSString stringWithFormat:@"%@?action=%@",UrlStr,dict[@"action"]];
            [dict removeObjectForKey:@"action"];
            NSArray *keyArr = dict.allKeys;
            NSMutableArray *valueArr = [NSMutableArray array];
            [keyArr enumerateObjectsUsingBlock:^(NSString * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                [valueArr addObject:[NSString stringWithFormat:@"%@=%@",obj,dict[obj]]];
            }];
            if (valueArr.count > 0) {

                UrlStr = [NSString stringWithFormat:@"%@&%@",UrlStr,[valueArr componentsJoinedByString:@"&"]];
            }
            Params = nil;
        }
    }

    NSURLSessionDataTask *dataTask = [mgr GET:UrlStr parameters:Params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

        [HUD hideHUD];
        Success (responseObject);

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

        [HUD hideHUD];
        Fail ? Fail (error):nil;
    }];

    return dataTask;
}

+ (NSURLSessionDataTask *)Post:(NSString *)UrlStr Auth:(BOOL)Auth Params:(NSDictionary *)Params Success:(void (^)(id))Success Fail:(void (^)(NSError *))Fail
{
    //1.获得请求管理者
    AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
    mgr.requestSerializer = [AFHTTPRequestSerializer serializer];
    mgr.responseSerializer = [AFHTTPResponseSerializer serializer];
    mgr.requestSerializer.timeoutInterval = 15;
    mgr.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/plain", @"text/html", nil];
    [mgr.requestSerializer setValue:@"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    //auth 加密
    if (Auth)
    {
        [mgr.requestSerializer setValue:[AccountTool shareAccountTool].currentAccount.authCode forHTTPHeaderField:@"auth"]; //Authorization
    }else {
        if (Params && Params.count > 0) {
            // 如果不用auth，那么action就一要跟在问号后面
            NSMutableDictionary *dict = [Params mutableCopy];
            UrlStr = [NSString stringWithFormat:@"%@?action=%@",UrlStr,dict[@"action"]];
            [dict removeObjectForKey:@"action"];
            NSArray *keyArr = dict.allKeys;
            NSMutableArray *valueArr = [NSMutableArray array];
            [keyArr enumerateObjectsUsingBlock:^(NSString * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                [valueArr addObject:[NSString stringWithFormat:@"%@=%@",obj,dict[obj]]];
            }];
            if (valueArr.count > 0) {

                UrlStr = [NSString stringWithFormat:@"%@&%@",UrlStr,[valueArr componentsJoinedByString:@"&"]];
            }
            Params = nil;
        }
    }


    NSURLSessionDataTask *dataTask = [mgr POST:UrlStr parameters:Params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

        [HUD hideHUD];

        NSError *Error = nil;
        NSDictionary *Json = [NSJSONSerialization JSONObjectWithData:responseObject options:(NSJSONReadingMutableLeaves) error:&Error];
        if (Error)
        {
            Success (responseObject);
        }
        else
        {
            Success (Json);
        }


    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

        [HUD hideHUD];
        Fail (error);
    }];

    return dataTask;
}

+ (NSURLSessionDownloadTask *)Down:(NSString *)UrlStr Auth:(BOOL)Auth Params:(NSDictionary *)Params completionHandler:(void (^)(NSURLResponse *response, NSURL *filePath, NSError *error))completionHandler {
    //远程地址
    NSURL *URL = [NSURL URLWithString:UrlStr];
    //默认配置
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];

    //AFN3.0+基于封住URLSession的句柄
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];

    //请求
    NSURLRequest *request = [NSURLRequest requestWithURL:URL];

    //下载Task操作
    NSURLSessionDownloadTask *dataTask = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {



    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {

        //- block的返回值, 要求返回一个URL, 返回的这个URL就是文件的位置的路径

        NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
        NSString *path = [cachesPath stringByAppendingPathComponent:response.suggestedFilename];
        return [NSURL fileURLWithPath:path];

    } completionHandler:completionHandler];

    [dataTask resume];
    return dataTask;
}


//图片以及其他信息上传
+ (void)UpdataImgWithURL:(NSString *)url pic:(id)image parameter:(NSDictionary *)paraDic success:(void (^)(id obj))success fail:(void (^)(NSError *error))fail
{
    //给相片指定本地路径
    NSString* documentPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *imagePath = [documentPath stringByAppendingPathComponent:@"123.png"];

    //保存本地
    NSData *imageData = UIImageJPEGRepresentation(image, 0.5);
    //保存到document
    [imageData writeToFile:imagePath atomically:YES];


    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];

    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/html", nil];
    [manager.requestSerializer setValue:[AccountTool shareAccountTool].currentAccount.authCode forHTTPHeaderField:@"auth"];

    [manager POST:url parameters:paraDic constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {

        [formData appendPartWithFileURL:[NSURL fileURLWithPath:imagePath] name:@"imgFile" error:nil];

    } progress:^(NSProgress * _Nonnull uploadProgress) {

    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

        [MBProgressHUD hideHUD];
        success (responseObject);

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

        [MBProgressHUD hideHUD];
        fail (error);

    }];
}

// 多张图片以及其他信息上传
+ (void)UpdataImgsWithURL:(NSString *)url imgs:(NSArray <UIImage *>*)imgs parameter:(NSDictionary *)paraDic Progress:(void (^)(NSProgress * _Nonnull uploadProgress))Progress success:(void (^)(id obj))success fail:(void (^)(NSError *error))fail
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.requestSerializer.timeoutInterval = 30;
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/html", nil];
    [manager.requestSerializer setValue:[AccountTool shareAccountTool].currentAccount.authCode forHTTPHeaderField:@"auth"];

    [manager POST:url parameters:paraDic constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {

        [imgs enumerateObjectsUsingBlock:^(UIImage * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            NSData *imageData = UIImageJPEGRepresentation(obj, 0.4);
            [formData appendPartWithFileData:imageData name:@"file" fileName:[NSString stringWithFormat:@"%ld.jpg",idx] mimeType:@"image/jpeg"];
        }];

    } progress:Progress success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

        [MBProgressHUD hideHUD];
        success (responseObject);

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

        [MBProgressHUD hideHUD];
        fail (error);

    }];
}



+ (void)UpdataAudioWithURL:(NSString *)url FilePath:(NSString *)FilePath parameter:(NSDictionary *)paraDic success:(void (^)(id))success fail:(void (^)(NSError *))fail
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];

    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/html", nil];
    [manager.requestSerializer setValue:[AccountTool shareAccountTool].currentAccount.authCode forHTTPHeaderField:@"auth"];

    [manager POST:url parameters:paraDic constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {

        [formData appendPartWithFileURL:[NSURL fileURLWithPath:FilePath] name:@"imgFile" error:nil];

    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        [MBProgressHUD hideHUD];
        success (responseObject);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        [MBProgressHUD hideHUD];
        fail (error);
        
    }];
}
@end
